const express = require('express');
const router = express.Router();
//导入加密包
const bcrypt = require('bcrypt');//加密
//导入jwt
const jwt = require('jsonwebtoken');
const { secret } = require('../../config/config')
const UserModel = require('../../models/UserModel');

//登入用户
router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    try {
        // 查询数据库
        const user = await UserModel.findOne({ username: username });
        // 判断用户是否存在
        if (!user) {
            return res.json({
                code: '2002',
                msg: '用户名不存在~~~',
                data: null,
      });
        }
        // 验证密码
        const match = await bcrypt.compare(password, user.password);
        if (!match) {
            return res.json({
                code: '2003',
                msg: '用户名或密码错误~~~',
                data:null
      });
        }
        // 创建当前用户的 token
        const token = jwt.sign({
            username: user.username,
            _id: user._id
        }, secret, {
            expiresIn: "7d" // 7天过期
        });
        // 响应 token
        res.json({
            code: '0000',
            msg: '登录成功',
            token
        });
    } catch (err) {
        console.error(err);
        res.json({
            code: '2001',
            msg: '数据库读取失败~~~',
            data:null
    });
    }
});

//退出登入
router.post('/logout', (req, res) => {
    //删除session
    req.session.destroy(() => {
        //重定向到登入页
        // res.redirect('/login');
        res.render('success', { msg: '退出成功', url: '/login' });
    })
});

module.exports = router;